package essay

import (
	"github.com/google/uuid"
	"html/template"
	"log"
	"net/http"

	essayStore "gitee.com/taadis/nook/store/essay"
	essayTemplate "gitee.com/taadis/nook/template/essay"
)

func init() {
	log.Println("init /essay/edit/ essayEdit")
	http.HandleFunc("/essay/edit/", essayEdit)
}

//
func essayEdit(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case http.MethodGet:
		getEssayEdit(w, r)
	case http.MethodPost:
		postEssayEdit(w, r)
	default:
		http.Error(w, "", http.StatusMethodNotAllowed)
	}
}

//
func getEssayEdit(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	id := r.FormValue("id")
	if id == ""{
		log.Println("id is empty")
		http.NotFound(w, r)
		return
	}

	data, err := essayTemplate.Data(id)
	if err != nil{
		log.Println("get essay data error:", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	filenames := []string{
		"template/root.tmpl",
		"template/essay_edit.tmpl",
	}
	tmpl, err := template.ParseFiles(filenames...)
	if err != nil {
		log.Println(err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	tmpl = template.Must(tmpl, err)
	err = tmpl.ExecuteTemplate(w, "root", data)
	if err != nil {
		log.Println(err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}

//
func postEssayEdit(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	id := r.PostFormValue("id")
	title := r.PostFormValue("title")
	content := r.PostFormValue("content")
	if id == "" {
		log.Println("id 为空, 表示新随笔")
		id = uuid.New().String()
		err := essayStore.Add(id, title, content)
		if err != nil {
			log.Println(err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
		http.Redirect(w, r, "/essay/?id=" + id, http.StatusFound)
	} else {
		log.Println("id 有值, 表示更新已有随笔")
		err := essayStore.Update(id, title, content)
		if err != nil {
			log.Println(err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
		http.Redirect(w, r, "/essay/?id=" + id, http.StatusFound)
	}
}
